import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import { useAuthStore } from '@/store/useAuthStore'
import { ResponseData } from './types'
import { message } from 'antd'

class UploadHttpRequest {
  // 文件上传专用实例
  private uploadInstance: AxiosInstance;
  
  constructor() {
    this.uploadInstance = axios.create({
      baseURL: this.getBaseURL(),
      timeout: 300000, // 5分钟超时，适合大文件上传
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
    
    this.setupInterceptors();
  }

  // 获取基础URL
  private getBaseURL(): string {
    if (import.meta.env.MODE === 'production') {
      return '/'
    }
    return 'http://127.0.0.1:8000'
  }

  // 设置拦截器
  private setupInterceptors(): void {
    // 请求拦截器
    this.uploadInstance.interceptors.request.use(
      (config) => {
        const token = useAuthStore.getState().token
        if (token) {
          config.headers.Authorization = `Token ${token}`
        }
        return config
      },
      (error) => {
        return Promise.reject(error)
      }
    )

    // 响应拦截器
    this.uploadInstance.interceptors.response.use(
      (response: AxiosResponse) => {
        return response
      },
      (error) => {
        // 处理超时错误
        if (error.code === 'ECONNABORTED' || error.message.includes('timeout')) {
          message.error('上传超时，请检查网络连接或尝试上传较小的文件');
          return Promise.reject(error);
        }
        
        // 处理其他错误
        if (error.response?.data?.message) {
          message.error(error.response.data.message);
        } else {
          message.error('上传失败，请稍后重试');
        }
        return Promise.reject(error)
      }
    )
  }

  // 文件上传方法
  public async upload<T = any>(url: string, data?: any, config?: AxiosRequestConfig) {
    return this.uploadInstance.post<ResponseData<T>>(url, data, config)
  }
}

// 创建单例实例
const uploadHttp = new UploadHttpRequest();

export default uploadHttp; 